// pages/order/myAllorder/myAllorder.js
var timer; // 计时器
var app =getApp();
var _PAGE = 1;
var _PAGESIZE = 10;
let load = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone_icon: '../../../images/phone_icon.png',
    token: wx.getStorageSync('token'),
    orderData:[],//订单列表
    searchKey: '', //搜索关键字
    reasonData: [],//退单原因列表
    reason: [],
    reasonIndex: "",
    placeholder: '商品是否给力？快分享你的购买心得吧~达到100字有额外奖励哦！',
    reasonShow: true,//
    chargebackId: '',//退还订单号
    remarks: '',//退还备注
    tipShow: true,//
    dropShow: true,//上门
    isOrderSureShow: false,//确认抢单
    workid: '', //接单id
    empty: true,
    hasMore: false,
    loading: false,
    loadShow: false,
    lat1: '',
    lng1: '',
    authInfo:{},
    callShow: false,//拨打电话弹窗显示
    callItem: '',// 点击拨打的工单详情
    callIndex: 0,//选择联系人|紧急联系人


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      searchKey: options.keyword || ''
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    _PAGE = 1;
    load = true;
    that.getOrderList(that.data.searchKey);



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that =this;
    that.setData({
      loadShow: false
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    var hasMore = that.data.hasMore;
    if(!hasMore){
      return false;
    }
    var searchKey = that.data.searchKey;
    _PAGE++;
    that.setData({
      loading: true
    })
    that.getOrderList(searchKey);
  },
  // 获取订单列表
  getOrderList: function (keywords){
    var that = this;
    var URL = 'Engineer/Workorder/repairWorkOrder';
    app.ajax({
      url: URL,
      method: "POST",
      load: load,
      msg: '数据加载中...',
      data:{
        keywords: keywords,
        page: _PAGE,
        pagesize: _PAGESIZE
      },
      header:{
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          if (_PAGE == 1) {
            that.setData({
              orderData: res.data.data,
              empty: false
            });
          } else {
            that.setData({
              orderData: that.data.orderData.concat(res.data.data),
              empty: false
            });
          }
          // 是否加载更多
          var hasMore = true;
          if (res.data.data.length < _PAGESIZE) {
            hasMore = false;
          }
          that.setData({
            hasMore: hasMore,
            loading: false
          });
          load = false;
        } else {
          if(_PAGE == 1){
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          }else{
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }

        }
        that.setData({
          loadShow: true
        })
      }
    })

  },
  // 输入搜索字段
  inputSearch:function(e){
    var that = this;
    var searchKey = e.detail.value;
    that.setData({
      searchKey: searchKey
    });
  },
  //小键盘直接搜索
  searchOrder: function(e){
    var that = this;
    var key = e.detail.value;
    // if(key == '' || key == null){
    //   app.showToast("请输入搜索关键字","none",2000,function(){});
    //   return;
    // }
    _PAGE = 1;
    that.setData({
      searchKey: key,
      empty: true,
      hasMore: false,
      loading: false,
      loadShow: false
    })
    load = true;
    that.getOrderList(key);
  },
  //点击搜索图标搜索
  searchOrder2: function(){
    var that = this;
    var key = that.data.searchKey;
    // if (key == '' || key == null) {
    //   app.showToast("请输入搜索关键字", "none", 2000, function () { });
    //   return;
    // }
    _PAGE = 1;
    that.setData({
      empty: true,
      hasMore: false,
      loading: false,
      loadShow: false
    })
    load = true;
    that.getOrderList(key);
  },
  // 打开拨打电话弹窗
  openCall(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log('index', index);
    var orderData = that.data.orderData;
    var item = orderData[index];
    console.log('item', item)
    that.setData({
      callShow: true,
      callItem: item,
      callIndex: 0

    })
  },
  // 关闭拨打电话弹窗
  cancelCall() {
    var that = this;
    that.setData({
      callShow: false,
      callItem: false
    })
  },
  // 跳转紧急联系人
  goEmergency() {
    var that = this;
    var callItem = that.data.callItem;
    wx.navigateTo({
      url: '../emergencyContact/emergencyContact?user_id=' + callItem.user_id + '&work_order_id=' + callItem.work_order_id + '&emergency_contact=' + JSON.stringify(callItem.emergency_contact),
    })
    that.cancelCall();
  },
  // 切换选择联系人|紧急联系人
  callChoose(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      callIndex: index
    })
  },
  // 确认选中拨打电话
  sureTelphone() {
    var that = this;
    var index = that.data.callIndex;
    var callItem = that.data.callItem;
    var number = callItem.contact_number;
    if (index == 1) {
      number = callItem.emergency_contact.tel
    }
    wx.makePhoneCall({
      phoneNumber: number,
    })
    that.cancelCall();
  },
  //联系他
  telPhone: function (e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  // 激活缴费器
  activation: function (e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../activation/activation?work_order_id=' + work_order_id,
    })
  },
  //获取退单原因列表
  getReturnReason: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getReturnReason',
      data: {},
      header: {
        'token': that.data.token
      },
      success: function (res) {
        var data = res.data.data;
        var reason = [];
        for (var i in data) {
          reason.push(data[i]);
        }
        that.setData({
          reasonData: data,
          reason: reason
        })

      }
    })
  },

  //退还订单
  chargeback: function (e) {
    let that = this;
    let reasonShow = false;
    let id = e.currentTarget.dataset.id;
    that.setData({
      reasonShow: reasonShow,
      chargebackId: id
    })
  },
  //退还原因
  bindPickerChange: function (e) {
    let that = this;
    let reasonIndex = e.detail.value;
    that.setData({
      reasonIndex: reasonIndex
    })
  },
  //退换备注
  inputRemarks: function (e) {
    var that = this;
    var remarks = e.detail.value;
    that.setData({
      remarks: remarks
    });
  },
  //确定退还
  confirm: function (e) {
    let that = this;
    let reasonShow = true;
    let tipShow = false;
    var id = that.data.chargebackId;
    var reasonIndex = that.data.reasonIndex;
    var remarks = that.data.remarks;
//    app.saveFormId(e.detail.formId);
    if (reasonIndex == '' || remarks == '') {
      app.showToast("请填写完整信息", "none", 2000, function () { });
      return;
    }
    app.ajax({
      url: 'Engineer/Workorder/backOrderApply',
      data: {
        work_order_id: id,
        reason_id: reasonIndex,
        remark: remarks
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("退单成功", "none", 2000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });

        }

      }
    })
    that.setData({
      reasonShow: reasonShow,
      tipShow: tipShow,
      remarks: '',
      reasonIndex: ''
    })
    timer = setTimeout(function () {
      let tipShow = true;
      that.setData({
        tipShow: tipShow
      })
      that.getOrderList();
    }, 2000);
  },
  //取消退还
  cancel: function () {
    let that = this;
    let reasonShow = true;
    that.setData({
      reasonShow: reasonShow,
      remarks: '',
      reasonIndex: ''
    })
  },
  //确认预约时间
  amendTime: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../amendTime/amendTime?id=' + id,
    })
  },
  //上门
  dropIn: function (e) {
    let that = this;
    let dropShow = false;
    var id = e.currentTarget.dataset.id;
    var lat1, lng1;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        lat1 = res.latitude;
        lng1 = res.longitude;

        that.setData({
          dropShow: dropShow,
          work_order_id: id,
          lat1: lat1,
          lng1: lng1
        })
      }
    });
  },
  //确定上门
  dropConfirm: function (e) {
    let that = this;
    let dropShow = true;
    var id = that.data.work_order_id;
    var lat1 = that.data.lat1;
    var lng1 = that.data.lng1;
   // app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Workorder/goHome',
      data: {
        work_order_id: id,
        lat: lat1,
        lng: lng1
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("确认成功", "none", 2000, function () { });
          wx.setStorageSync('tabIndex',2);
          that.getOrderList();
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })

    that.setData({
      dropShow: dropShow
    })
  },
  //取消上门
  dropCancel: function () {
    let that = this;
    let dropShow = true;
    that.setData({
      dropShow: dropShow
    })
  },
  // 确认安装地址
  confirmAddress(e) {
    var that = this;
    var order_id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    if (type != 2) {
      type = 1;
    }
    wx.navigateTo({
      url: '../confirmAddress/confirmAddress?order_id=' + order_id + '&type=' + type,
    })
  },
  //导航
  orderMap: function (e) {
    var lat = parseFloat(e.currentTarget.dataset.lat)
    var lng = parseFloat(e.currentTarget.dataset.lng)
    wx.openLocation({
      latitude: lat,
      longitude: lng,
      scale: 28
    })
  },
  // 绑定缴费器
  bindEquipment: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../order/import/import?id='+id,
    })
  },
  //完成订单
  completeOrder: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    app.ajax({
      url: 'Engineer/Workorder/editWorkStatus',
      method: 'POST',
      data: { work_order_id: id },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("工单已完成", "none", 2000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
        _PAGE = 1;
        that.getOrderList();
      }
    })
  },
  //查看详情
  orderDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../orderDetail/orderDetail?id=' + id,
    })
  },
  //完成
  finishOn(e){
    var that = this;
    wx.removeStorageSync('basics');//清除缓存
    wx.removeStorageSync('filterelement');//清除缓存
    wx.removeStorageSync('service');//清除缓存
    wx.removeStorageSync('valcontent');//清除缓存
    wx.removeStorageSync('showImg');//清除缓存
    wx.removeStorageSync('upImg');//清除缓存
    wx.removeStorageSync('armature');//清除缓存
    wx.removeStorageSync('need_charge');//清楚缓存
    var finishId = e.currentTarget.dataset.id;
    that.setData({
      finishId: finishId,
    })
    wx.navigateTo({
      url: '../newreceipt/newreceipt?id=' + finishId,
    })
  },

  //签合同
  sign: function (e) {
    wx.navigateTo({
      url: '../../myCenter/econtract/econtract?contract_id=' + e.currentTarget.dataset.contract_id + "&user_id=" + e.currentTarget.dataset.user_id,
    })
  },

  //跳转我的认证
  authentication(e) {
    var that = this;
    var user_id = e.currentTarget.dataset.user_id;
    app.ajax({
      url: "Engineer/Realname/getAuthInfo",
      data: { user_id: user_id },
      success: function (res) {
        if (res.data.code == 1000 && res.data.data.status == -2) {
            wx.navigateTo({
              url: '../../realname/uploadDocuments/uploadDocuments?user_id='+user_id,
            })
        } else if (res.data.code == 1000 && res.data.data.status == -3) {
            wx.navigateTo({
              url: '../../realname/faceRecognition/faceRecognition?user_id='+user_id,
            })
        } else if (res.data.code == 1000 && (res.data.data.status == 2 || res.data.data.status == 1)) {
          wx.navigateTo({
            url: '../../realname/myCertification/myCertification?user_id=' + user_id,
          })
        } else {
            wx.navigateTo({
              url: '../../realname/realName/realName?user_id='+user_id,
            })
          }
        }

    })


  },

  // 接单
  takeOrderReceipt: function (e) {
    var that = this;
    that.setData({
      isOrderSureShow: true,
      workid: e.currentTarget.dataset.id
    })

  },
  // 阻止遮罩滚动
  myCatchTouch: function () {
    return;
  },
  // 取消接单
  orderCancel: function () {
    this.setData({
      isOrderSureShow: false,
      workid: ''
    })
  },
  // 确认接单
  orderSure: function (e) {
    var that = this;
   // app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Order/receiveOrder',
      data: { work_order_id: that.data.workid },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "none", 2000, function () { });
          that.getOrderList();
        }
      }
    });
    that.setData({
      isOrderSureShow: false
    })
  },
  //企业用户签合同
  signTip() {
    app.showToast("该用户非个人客户,请告知客户登录用户端小程序进行签署!")
  },

})
